<?php
/**
 * ============================================================================
 * @package Forum
 * @author Andy
 * @version 9:41
 * @link https://sjdphp.com
 * ----------------------------------------------------------------------------
 */

namespace app\install\controller;


use app\BaseController;
use app\common\model\Back;
use app\common\server\Json;
use app\common\server\SystemLog;
use app\common\server\Tools;

class Index extends BaseController
{

    // 初始化
    public function initialize(){
        // 判断是否安装过
        if(is_file(dirname(__FILE__) . '/../data/install.lock')){
            return redirect("/index")->send();
        }
    }

    /** 环境检测
     * @return \think\response\View
     */
    public function index(){
        ## 环境检测
        $envs = checkEnv();
        ## 目录/文件检测
        $dirFiles = checkDirFile();
        ## 函数检测
        $funs     = checkFunc();

        return view('',[
            'title'    => 'ZzPHP安装系统--环境检查',
            'envs'     => $envs,
            'dirFiles' => $dirFiles,
            'funcs'    => $funs
        ]);
    }

    /** 参数配置
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function system(){
       if($this->request->isPost()){
            ## 接收参数并校验
            $param['username'] = $this->request->param("username",'','trim');
            $onePwd   = $this->request->param("onePwd",'','trim');
            $twoPwd   = $this->request->param("twoPwd",'','trim');
            $param['back_name']  = $this->request->param("real",'','trim');
            $param['back_email'] = $this->request->param("email",'','trim');

            if(empty($param["username"])) return Json::error("用户名不能为空");
            if($onePwd !== $twoPwd) return Json::error("两次密码输入的不一致,请重新输入");

            ## 判断创建的用户名是否重复
            $info = Back::where("username",$param["username"])->find();

            if(!empty($info)) return Json::success("设置成功");

            ## 生成密码密钥
            $param["back_key"] = Tools::getRandStr(32);
            ## 加密密码
            $param["password"] = Tools::md5AdminPwd($onePwd,$param["back_key"]);
            $param["role_id"]  = 1;
            $param["role_name"] = '开发者';
            $param["back_status"] = 1;

            ## 入库生成
            try{
               $res = Back::create($param);
            }catch(\Exception $e){
               SystemLog::insertLog($e->getMessage());
            }

            if(!empty($res)){

               return Json::success("设置成功");
            }else{
               return Json::error("设置失败");
            }
       }else{
           return view('',[
               'title' => 'ZzPHP安装系统--参数配置',
           ]);
       }
    }

    /** 安装数据库
     * @return \think\response\Json|\think\response\View
     */
    public function db(){
        if($this->request->isPost()){
            ## 接受并校验数据
            $type     = $this->request->param("type",'mysql','trim');
            $host     = $this->request->param('host','127.0.0.1','trim');
            $port     = $this->request->param('port','3306','trim');
            $database = $this->request->param('database','ZzPHP','trim');
            $username = $this->request->param('username','root','trim');
            $password = $this->request->param('password','','trim');
            $prefix   = $this->request->param('prefix','zz_','trim');

            if(empty($host)) return Json::error("数据库地址不能为空");
            if(empty($port)) return Json::error("数据库端口不能为空");
            if(empty($database)) return Json::error("数据库名称不能为空");
            if(empty($username)) return Json::error("数据库账号不能为空");
            if(empty($prefix)) return Json::error("数据表前缀不能为空");

            ## 创建数据库
            if(!class_exists('Pdo')){
                return Json::error('安装失败，请确保您的环境支持pdo扩展！');
            }
            $dsn = "mysql:host=" . $host . ";port=" . $port. ";charset=utf8";
            $link = null;
            try{
                $link = new \PDO($dsn,$username,$password);
            }catch(\PDOException $e){
                return Json::error("数据库连接失败，请检查连接信息是否正确或者数据库是否存在！错误信息:" . $e->getMessage());
            }
            if (!$link) {
                return Json::error('数据库连接失败，请检查连接信息是否正确或者数据库是否存在！');
            }
            $link->exec("SET NAMES UTF-8");
            ## 创建数据库并选中
            if (!$link->query("use ".$database)) {
                $create_sql = 'CREATE DATABASE IF NOT EXISTS '.$database.' DEFAULT CHARACTER SET utf8;';
                $link->exec($create_sql) or die(print_r($link->errorInfo(), true));
                $link->query("use ".$database);
            }

            ## 创建表
            $sqlFile = dirname(__FILE__) . '/../data/zz.sql';
            if(!is_file($sqlFile)){
                return Json::error("数据库文件不存在");
            }
            $sql = file_get_contents(dirname(__FILE__) . '/../data/zz.sql');
            ## 替换表前缀
            $sql = str_replace(["\r"," `zz_"], ["\n"," `{$prefix}"], $sql);
            $sql = explode(";\n", $sql);

            foreach ($sql as $value) {
                $value = trim($value);
                if (empty($value)) continue;
                if(substr($value, 0, 12) == 'CREATE TABLE') {
                    if(false===$link->exec($value)) return Json::error("创建失败");
                }else{
                    $link->exec($value);
                }
            }

            ## 读取配置文件
            $envFile = file_get_contents(dirname(__FILE__) . '/../data/.env');
            ## 替换配置文件
            $envFile = str_replace("HOSTNAME = 127.0.0.1",'HOSTNAME = '. $host,$envFile);
            $envFile = str_replace("DATABASE = zz",'DATABASE = '. $database,$envFile);
            $envFile = str_replace("USERNAME = root",'USERNAME = '. $username,$envFile);
            $envFile = str_replace("PASSWORD = root",'PASSWORD = '. $password,$envFile);
            $envFile = str_replace("HOSTPORT = 3306",'HOSTPORT = '. $port,$envFile);
            $envFile = str_replace("PREFIX = zz_",'PREFIX = '. $prefix,$envFile);

            ## 重新写入
            file_put_contents(__DIR__ . '/../../../.env',$envFile);
            ## 复制文件到根目录下
           // copy(dirname(__FILE__) . '/../data/.env',__DIR__ . '/../../../.env');


            return Json::success("创建成功");
        }else{
            return view('',[
                'title' => 'ZzPHP安装系统--数据库安装',
            ]);
        }
    }


    public function success(){
        if($this->request->isPost()){
            ## 创建安装文件
            file_put_contents(dirname(__FILE__) . '/../data/install.lock',time());
            return Json::success("success");
        }else{
            return view('',[
                'title' => 'ZzPHP安装系统--安装完成',
            ]);
        }

    }
}